import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:kxy_flutter_app/auth.dart';
import 'package:kxy_flutter_app/components/refresh_header.dart';
import 'package:kxy_flutter_app/helper/http.dart';
import 'package:kxy_flutter_app/model/course.dart';
import 'package:kxy_flutter_app/model/exam.dart';
import 'package:kxy_flutter_app/model/home.dart';
import 'package:kxy_flutter_app/model/news.dart';
import 'package:kxy_flutter_app/r.dart';
import 'package:kxy_flutter_app/view/home/home_course_widget.dart';
import 'package:kxy_flutter_app/view/home/home_exam_widget.dart';
import 'package:kxy_flutter_app/view/home/home_news_widget.dart';
import 'package:kxy_flutter_app/view/root/view_model/app_info_model.dart';
import 'package:kxy_flutter_app/view/root/view_model/navigation_model.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'home_banner_widget.dart';
import 'home_cate_widget.dart';
import 'notice/notice_widget.dart';

class HomeView extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return HomeViewState();
  }
}

class HomeViewState extends State<HomeView> with AutomaticKeepAliveClientMixin {
  int noReadCount;
  List<News> newsList;
  List<Exam> examList;
  List<News> partyNewsList;
  List<HomeBanner> bannerList;
  List<HomeCategory> cateList;
  List<CourseProfile> courseList;
  RefreshController refreshController = new RefreshController();

  Future loadFuture;

  @override
  void initState() {
    super.initState();
    loadFuture = load();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      appBar: AppBar(
        title: Consumer<AppInfoModel>(
          builder: (cxt, vm, child) {
            return Text(vm.homeTitle);
          },
        ),
        centerTitle: true,
        leading: Consumer<AppInfoModel>(
          builder: (cxt, vm, child) {
            return Container(
              margin: EdgeInsets.fromLTRB(10, 10, 10, 10),
              child: vm.logoUrl.isEmpty
                  ? Image.asset(R.assetsCommonLogo)
                  : CachedNetworkImage(
                      imageUrl: vm.logoUrl,
                      fit: BoxFit.fitHeight,
                    ),
            );
          },
        ),
        actions: [
          Consumer<NavigationModel>(builder: (cxt, navModel, child) {
            return NoticeWidget(noReadCount: navModel.noticeCount);
          }),
        ],
      ),
      body: FutureBuilder(
        future: loadFuture,
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            return body();
          }
          return Container();
        },
      ),
    );
  }

  Widget body() {
    var scrollView = SingleChildScrollView(
      padding: EdgeInsets.symmetric(vertical: 10),
      child: Column(
        children: [
          if (bannerList.length > 0) HomeBannerWidget(bannerList: bannerList),
          if (cateList.length > 0) HomeCateWidget(cateList: cateList),
          if (examList.length > 0) HomeExamWidget(examList: examList),
          if (courseList.length > 0) HomeCourseWidget(courseList: courseList),
          if (newsList.length > 0) HomeNewsWidget(newsList: newsList, partyNewsList: partyNewsList),
        ],
      ),
    );

    return SmartRefresher(
      controller: refreshController,
      enablePullDown: true,
      enablePullUp: false,
      header: RefreshHeader(),
      onRefresh: () async {
        var navModel = Provider.of<NavigationModel>(context, listen: false);
        await navModel.refreshNoticeCount(withNotify: false);
        await load();
        refreshController.refreshCompleted();
      },
      child: scrollView,
    );
  }

  Future load() async {
    var res = await Http.instance.post('/index', params: {
      'userId': Auth.instance.userId,
      'courseCount': 4,
      'examCount': 5,
      'newsCount': 5,
      'partyNewsCount': 5,
    });
    if (res.code == 200) {
      setState(() {
        examList = (res.data['examList'] as List).map((e) => Exam.fromJson(e)).toList();
        newsList = (res.data['newsList'] as List).map((e) => News.fromJson(e)).toList();
        partyNewsList = (res.data['partyNewsList'] as List).map((e) => News.fromJson(e)).toList();
        bannerList = (res.data['bannerList'] as List).map((e) => HomeBanner.fromJson(e)).toList();
        courseList = (res.data['courseList'] as List).map((e) => CourseProfile.fromJson(e)).toList();
        cateList = (res.data['cateList'] as List).map((e) => HomeCategory.fromJson(e)).toList();
      });
    } else {
      Fluttertoast.showToast(msg: res.msg);
    }
  }

  @override
  bool get wantKeepAlive => true;
}
